package com.common.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.annotation.CheckEquipment;
import com.common.annotation.LogAnnotation;
import com.common.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.common.controller.base.BaseAjaxController;
import com.common.dto.AccountInfoDTO;
import com.common.dto.PersonInfoDTO;
import com.common.service.AccountInfoService;
import com.common.service.PersonInfoService;

@Controller
@RequestMapping("/account")
public class AccountInfoController extends BaseAjaxController<AccountInfoDTO> {

	@Autowired
	private AccountInfoService accountInfoService;

    @Autowired
    private PersonInfoService personInfoService;
	

    /**
     * 微信扫码登录控制
     */
    private String weChatAuthorizedPerson = null;


	@RequestMapping(ConstantDefine.LOGIN_REQ)
	public ResponseEntity<Map<String, Object>> login(AccountInfoDTO account,HttpServletRequest request){
		Map<String,Object> result = accountInfoService.login(account,request);
        return WebUtil.getResponseEntity(result);
	}

    /**
     * 获取用户信息
     * @param account
     * @return
     */
    @RequestMapping("/getDetails")
    public ResponseEntity<Map<String, Object>> getDetails(AccountInfoDTO account){
        Map<String, Object> result = new HashMap<>();
        Object obj = ShiroUtil.getSessionByKey(ConstantDefine.PERSONCODE_SESSION);
        if(null != obj){
            String personCode = obj.toString();
            account.setPersonCode(personCode);
            account = accountInfoService.selectByDTO(account);
            PersonInfoDTO personInfo = personInfoService.selectByPersonCode(personCode);
            personInfo.setAccountCode(account.getAccountCode());
            result.put("personInfo",personInfo);
        }
        return WebUtil.getResponseEntity(result);
    }

    /**
     * 选择绑定账号类型
     * @param model 向页面传递数据
     * @return
     */
	@Override
	public String init(Model model) {
		return "personal/account";
	}

	
	/**
	 * 验证验证码是否有效
	 * 
	 * @param verityCode
	 * @param request
	 * @return
	 */
	@RequestMapping("/verityCode")
	@ResponseBody
	public Map<String, Object> verityCode(String verityCode, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String ranCode = (String) request.getSession().getAttribute("code");
		String before = (String) request.getSession().getAttribute("before");
		if (!"".equals(ranCode) && null != ranCode && !"".equals(verityCode) && null != verityCode) {
			String after = DateUtil.getSystemTimeStr();
			int minutesBetween = DateUtil.minutesBetween(before, after);
			if (ranCode.equals(verityCode)) {
				if (minutesBetween <= 1) {
					resultMap.put(ConstantDefine.FLAG, "1");
					resultMap.put(ConstantDefine.CHECK_ERR_MSG, "验证码输入正确!");
				} else {
					resultMap.put(ConstantDefine.FLAG, "0");
					resultMap.put(ConstantDefine.CHECK_ERR_MSG, "验证码已经失效!");
				}
			} else {
				resultMap.put(ConstantDefine.FLAG, "0");
				resultMap.put(ConstantDefine.CHECK_ERR_MSG, "验证码输入错误!");
			}
		} else {
			resultMap.put(ConstantDefine.FLAG, "0");
			resultMap.put(ConstantDefine.CHECK_ERR_MSG, "验证码为空!");
		}
		if (resultMap.get(ConstantDefine.FLAG).equals("1")) {
			request.removeAttribute("code");
		}
		return resultMap;
	}
	
	/**
	 * 验证内部账号是否存在
	 * 	
	 * @author wuronglai
	 * @return
	 */
    @ResponseBody
	@RequestMapping("/checkAccount")
	public Map<String, Object> checkAccount(AccountInfoDTO accountInfo){
		Map<String, Object> resultMap = accountInfoService.check(accountInfo);
		return resultMap;
	}


	@Override
	public AccountInfoDTO updateInit(String id) {
		return null;
	}

	@Override
	public ResponseEntity<Map<String, Object>> update(AccountInfoDTO entity, BindingResult bindingResult) {
		return null;
	}

	@Override
	public ResponseEntity<Map<String, Object>> delete(List<String> id) {
		return null;
	}


	@Override
	public ResponseEntity<Map<String, Object>> save(AccountInfoDTO entity, BindingResult bindingResult) {
		return null;
	}


	@Override
	public String init(AccountInfoDTO entity, Model model) {
		String typeStr = entity.getType();
		return "personal/"+typeStr;
	}

	@Override
	public Object queryByEntity(AccountInfoDTO entity) {
		return null;
	}

    /**
     * 获取当前登录用户权限
     * @author wrl
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/authority",method = RequestMethod.GET)
    public Object authority() {
        String personCode= (String) ShiroUtil.getSessionByKey(ConstantDefine.PERSONCODE_SESSION);
        List<String> list =accountInfoService.selectAuthorityList(personCode);
        return list;

    }

    /**
     * Created by wrl on 2017/07/22
     * 加载图片验证码
     *
     * @param response
     */
    @RequestMapping("/code")
    public void verification(HttpServletRequest request,HttpServletResponse response) {
        String code = VerityCodeUtil.getAuthCode();
        SecurityUtils.getSubject().getSession().setAttribute("code", code);
        // 发送图片验证码
        try {
            ImageIO.write(VerityCodeUtil.getAuthImg(code), "PNG", response.getOutputStream());
            String before = DateUtil.getSystemTimeStr();
            SecurityUtils.getSubject().getSession().setAttribute("before", before);
            logger.info("verify code:["+code+"] ； before:["+before+"]");
        } catch (IOException e) {
            logger.error("发送验证码图片异常send verify code exception："+e);
        }
    }

    /**
     * Created by wrl on 2017/07/10
     * @param entity
     * @param request
     * @return
     */
    @RequestMapping("/amdinLogin")
    @LogAnnotation(description = "后台人员登录", bizID = LogType.ACCOUNT)
    public ResponseEntity<Map<String,Object>> amdinLogin(AccountInfoDTO entity, HttpServletRequest request){
        Map<String, Object> map = accountInfoService.login(entity,request);
        if((boolean)map.get(ConstantDefine.FLAG)) map.put("page","page/index.html");

        return WebUtil.getResponseEntity(map);
    }
    
    /**
     * Created by sunyang on 2017/12/07
     * @param entity
     * @param request
     * @return
     */
    @RequestMapping(value = "appLogin",produces = "application/json;charset=utf-8") 
    @ResponseBody
    public String appLogin(AccountInfoDTO entity, HttpServletRequest request){
        Map<String, Object> map = accountInfoService.login(entity,request);
        if((boolean)map.get(ConstantDefine.FLAG)) map.put("page","page/index.html");
        return JSON.toJSONString(map);
    }

    

    /**
     * 管理员修改用户密码
     * Created by wrl on 2017/07/22
     * @return
     */
    @ResponseBody
    @RequestMapping("/changePwd")
    @LogAnnotation(description = "修改密码", bizID = LogType.ACCOUNT)
    public Map<String,Object> updateAccountPwd(AccountInfoDTO accountInfo){
        Map<String, Object> map =accountInfoService.changePwd(accountInfo);
        return map;
    }

    /**
     * 生成二维码
     * Created by wrl on 2017/07/24
     * @return
     */
    @RequestMapping("/qrcode")
    public ResponseEntity<Map<String,Object>> getQRCode(){
        //公众号二维码
        Map<String,Object> map = new HashMap<>();
        map.put("qrcode","\\slcclms\\img\\qrcode.png");
        return WebUtil.getResponseEntity(map);
    }


    /**
     * 成功授权
     * Created by wrl on 2017/07/24
     * @return
     */
    @ResponseBody
    @RequestMapping("/adminSuccess")
    public Map<String,Object> adminSuccess(AccountInfoDTO accountInfoDTO,HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        if(null != weChatAuthorizedPerson){
            accountInfoDTO.setPersonCode(weChatAuthorizedPerson);
            System.err.println(weChatAuthorizedPerson);
            accountInfoDTO = accountInfoService.selectByDTO(accountInfoDTO);
            accountInfoDTO = accountInfoService.decryptAccountPwd(accountInfoDTO);
            Map<String, Object> resultMap = accountInfoService.login(accountInfoDTO, request);
            if((boolean)resultMap.get(ConstantDefine.FLAG)){
                System.err.println("登录成功！");
                map.put("page","adminModel/index.html");
                return map;      //登录成功
            }
            weChatAuthorizedPerson = null;
        }
        System.err.println("登录失败！");
        return null;
    }
    
    @RequestMapping("/logout")
    @LogAnnotation(description = "退出登录", bizID = LogType.ACCOUNT)
    public String logout() {
    	try {
			Subject subject = SecurityUtils.getSubject();
			subject.logout();
		} catch (Exception e) {
			return "redirect:/";
		}
    	return "redirect:/";
	}
}
